<template>
  <div class="car-info-page">
    <!-- 页面标题 -->
    <el-page-header @back="goBack" content="租车服务" class="page-header" />

    <!-- 搜索条件区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" label-width="80px" label-position="left">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="车牌号">
                <el-input
                  v-model="searchForm.plate"
                  placeholder="请输入车牌号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="车辆类型">
                <el-select
                  v-model="searchForm.ctypeid"
                  placeholder="请选择车辆类型"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in carTypes"
                    :key="item.ctypeid"
                    :label="item.ctypename"
                    :value="item.ctypeid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="车辆品牌">
                <el-select
                  v-model="searchForm.brandid"
                  placeholder="请选择车辆品牌"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in carBrands"
                    :key="item.brandid"
                    :label="item.brandname"
                    :value="item.brandid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="价格区间">
                <div class="price-range">
                  <el-input
                    v-model="searchForm.minPrice"
                    placeholder="最低价"
                  />
                  <span>-</span>
                  <el-input
                    v-model="searchForm.maxPrice"
                    placeholder="最高价"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="地理位置">
                <el-cascader
                  v-model="selectedLocation"
                  :options="locationOptions"
                  :props="locationProps"
                  placeholder="请选择地区"
                  clearable
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label=" ">
                <div class="search-actions">
                  <el-button type="primary" @click="searchCars">搜索</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>

    <!-- 车辆列表 -->
    <div class="car-list">
      <el-row :gutter="20">
        <el-col
          v-for="car in carList"
          :key="car.carid"
          :span="8"
          class="car-col"
        >
          <el-card class="car-card" shadow="hover">
            <img :src="car.pictures" class="car-image" />
            <div class="car-details">
              <h3>{{ car.carname }}</h3>
              <p>品牌: {{ car.brandname }}</p>
              <p>类型: {{ car.ctypename }}</p>
              <p>价格: ¥{{ car.price }}/天</p>
              <p>站点: {{ car.lname }}</p>
              <div class="car-actions">
                <el-button
                  type="primary"
                  size="small"
                  @click="viewCarDetail(car)"
                  >查看详情</el-button
                >
                <el-button type="success" size="small" @click="rentCar(car)"
                  >立即租车</el-button
                >
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[9, 18, 36]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="carList.length === 0 && !loading"
      description="暂无车辆信息"
    />

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-skeleton
        v-for="i in 6"
        :key="i"
        style="width: 33%; padding: 10px"
        animated
      >
        <template #template>
          <el-skeleton-item
            variant="image"
            style="width: 100%; height: 200px"
          />
          <div style="padding: 14px">
            <el-skeleton-item variant="h3" style="width: 50%" />
            <div>
              <el-skeleton-item variant="text" style="margin-right: 16px" />
              <el-skeleton-item variant="text" style="width: 30%" />
            </div>
          </div>
        </template>
      </el-skeleton>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import api from "@/util/service";

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  plate: "",
  ctypeid: "",
  brandid: "",
  minPrice: "",
  maxPrice: "",
  lid: "",
});

// 车辆数据
const carList = ref([]);
const carTypes = ref([]);
const carBrands = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(9);
const total = ref(0);
const loading = ref(false);

// 地理位置相关
const locationOptions = ref([]);
const selectedLocation = ref([]);

const locationProps = {
  value: "id",
  label: "name",
  children: "children",
  lazy: true,
  lazyLoad: async (node, resolve) => {
    const { level, value } = node;
    let nodes = [];

    if (level === 0) {
      // 加载省份
      const res = await api.get("/position/getAllProvince");
      if (res.code === 200) {
        nodes = res.data.map((province) => ({
          id: province.pid,
          name: province.pname,
          leaf: false,
        }));
      }
    } else if (level === 1) {
      // 加载城市
      const res = await api.get(`/position/getCityByPid/${value}`);
      if (res.code === 200) {
        nodes = res.data.map((city) => ({
          id: city.cid,
          name: city.cname,
          leaf: false,
        }));
      }
    } else if (level === 2) {
      // 加载站点
      const res = await api.get(`/position/getLocationByCid/${value}`);
      if (res.code === 200) {
        nodes = res.data.map((location) => ({
          id: location.lid,
          name: location.lname,
          leaf: true,
        }));
      }
    }

    resolve(nodes);
  },
};

// 监听地理位置选择变化
const watchLocationChange = () => {
  if (selectedLocation.value.length > 0) {
    searchForm.lid = selectedLocation.value[selectedLocation.value.length - 1];
  } else {
    searchForm.lid = "";
  }
};

// 获取车辆类型
const fetchCarTypes = async () => {
  try {
    const res = await api.get("/carTpye/selectCarTpye");
    if (res.code === 200) {
      carTypes.value = res.data;
    }
  } catch (error) {
    ElMessage.error("获取车辆类型失败");
  }
};

// 获取车辆品牌
const fetchCarBrands = async () => {
  try {
    const res = await api.get("/carTpye/selectCarBrand");
    if (res.code === 200) {
      carBrands.value = res.data;
    }
  } catch (error) {
    ElMessage.error("获取车辆品牌失败");
  }
};

// 获取车辆列表
const fetchCars = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    };

    // 清理空值参数
    Object.keys(params).forEach((key) => {
      if (
        params[key] === "" ||
        params[key] === null ||
        params[key] === undefined
      ) {
        delete params[key];
      }
    });

    const res = await api.post("/tcar/selectCars", params);
    if (res.code === 200) {
      carList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error("获取车辆列表失败");
    }
  } catch (error) {
    ElMessage.error("获取车辆列表失败: " + error.message);
  } finally {
    loading.value = false;
  }
};

// 搜索车辆
const searchCars = () => {
  watchLocationChange();
  currentPage.value = 1;
  fetchCars();
};

// 重置表单
const resetForm = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  selectedLocation.value = [];
  currentPage.value = 1;
  fetchCars();
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchCars();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchCars();
};

// 查看车辆详情
const viewCarDetail = (car) => {
  sessionStorage.setItem("carId", car.carid);
  router.push("/CarDetails");
};

// 租车
const rentCar = (car) => {
  sessionStorage.setItem("carId", car.carid);
  router.push("/RentCar");
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 初始化数据
onMounted(() => {
  fetchCarTypes();
  fetchCarBrands();
  fetchCars();
});
</script>

<style scoped>
.car-info-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-actions {
  display: flex;
  gap: 10px;
}

.car-col {
  margin-bottom: 20px;
}

.car-card {
  border-radius: 8px;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.car-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.car-details {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.car-details h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.car-details p {
  margin: 5px 0;
  color: #666;
  flex-grow: 1;
}

.car-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.loading {
  display: flex;
  flex-wrap: wrap;
}

@media (max-width: 1200px) {
  .el-col {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .el-col {
    width: 100%;
  }

  .car-info-page {
    padding: 10px;
  }
}
</style>
